using B.S.Meeting.ErrorCode;
using B.S.Meeting.Infrastructure.Interfaces;
using B.S.Meeting.WriteAPI.Applications.Commands.Users;
using MediatR;

namespace B.S.Meeting.WriteAPI.Applications.CommandHandlers.Users
{
    public class SendCodeCommandHandler : IRequestHandler<SendCodeCommand, APIResult<string>>
    {
        private readonly IVerificationCodeService _verificationCodeService;
        private readonly ILogger<SendCodeCommandHandler> _logger;

        public SendCodeCommandHandler(
            IVerificationCodeService verificationCodeService,
            ILogger<SendCodeCommandHandler> logger)
        {
            _verificationCodeService = verificationCodeService ?? throw new ArgumentNullException(nameof(verificationCodeService));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }

        public async Task<APIResult<string>> Handle(SendCodeCommand request, CancellationToken cancellationToken)
        {
            try
            {
                if (string.IsNullOrEmpty(request.Phone))
                {
                    _logger.LogWarning("发送验证码失败：手机号为空");
                    return new APIResult<string>
                    {
                        Code = StatusEnumCode.Fail,
                        Message = "手机号不能为空",
                        Data = null
                    };
                }

                // 生成验证码
                string verificationCode = await _verificationCodeService.GenerateCodeAsync(request.Phone);

                // TODO: 这里应该调用短信服务发送验证码
                // 目前仅返回验证码，实际项目中需要对接短信服务
                _logger.LogInformation($"向手机号 {request.Phone} 发送验证码：{verificationCode}");

                return new APIResult<string>
                {
                    Code = StatusEnumCode.Ok,
                    Message = "验证码发送成功",
                    Data = verificationCode // 实际项目中不应该返回验证码
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"发送验证码失败: {request.Phone}");
                return new APIResult<string>
                {
                    Code = StatusEnumCode.Fail,
                    Message = "验证码发送失败",
                    Data = null
                };
            }
        }
    }
} 